package mcom.xmks.bluetooth.mesh.base;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.util.ArrayList;
import java.util.List;

import cn.wch.meshlib.core.ConCallback;
import cn.wch.meshlib.core.MeshServer;
import mcom.xmks.bluetooth.mesh.dialog.DialogUtil;
import mcom.xmks.bluetooth.mesh.dialog.UserDialog;
import mcom.xmks.bluetooth.mesh.utils.ToastUtil;

public abstract class BaseActivity extends AppCompatActivity {
    /**将框架显示为子集*/
    private static final String EXTRA_SHOW_FRAGMENT_AS_SUBSETTING =":settings:show_fragment_as_subsetting";
    private static final int REQUEST_BLUETOOTH_CODE=121;
    private boolean isConnected=false;
    private BaseActivity self = this;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView();
        initWidget();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==this.REQUEST_BLUETOOTH_CODE){
            boolean isManualPermission=false;  //手动权限
            String denied="";
            for(int i=0;i<permissions.length;i++) {
                int grantResult = grantResults[i];
                if(grantResult==PackageManager.PERMISSION_GRANTED){
                    Log.e("requestPermissions",permissions[i]+"权限被允许。");
                }else {
                    //呗禁用，应道用户到设置页面
                    isManualPermission=true;
                    if(denied.length()>0){
                        denied+=","+permissions[i];
                    }else{
                        denied=permissions[i];
                    }
                    Log.e("requestPermissions", permissions[i] + "权限被禁止，请在系统设置里面授权该权限。");
                }
            }
            if(isManualPermission){
                UserDialog dialog=new UserDialog(this, "权限请求",
                        denied + "权限请求被拒，需要在系统设置页开启这些权限。进入到系统设置页开启吗？",
                        new UserDialog.OnConfirmListener() {
                            @Override
                            public void onConfirm(DialogInterface dialog) {
                                dialog.dismiss();
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.setData(Uri.fromParts("package" , getPackageName(),null));
                                intent.putExtra("type", "110");
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                //显示为子框架（子框架下标题栏会显示返回图标）
                                intent.putExtra(EXTRA_SHOW_FRAGMENT_AS_SUBSETTING,true);
                                intentActivityResultLauncher.launch(intent);
                            }
                        });
                dialog.setConfirmTitle("是");
                dialog.setCancelTitle("否");
                dialog.show();
            }
        }
    }
    @Override
    public void onBackPressed() {
        if(MeshServer.getInstance().isConnected()){
            DialogUtil.getInstance().showDisconnectDialog(this, new DialogUtil.IDisconnectResult() {
                @Override
                public void onDisconnect() {
                    disconnect(false);
                }
                @Override
                public void onCancel() {
                }
            });
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disconnect(true);
    }

    abstract void setView();
    abstract void initWidget();

    private  String[] getRuntimePermissions(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
            return new String[]{Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.BLUETOOTH_ADVERTISE,Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION};
        }else{
            return new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
        }
    }
    public boolean checkPermissionsAllowed(){
        for (String runtimePermission : getRuntimePermissions()) {
            if(ActivityCompat.checkSelfPermission(this,runtimePermission)!= PackageManager.PERMISSION_GRANTED){
                return false;
            }
        }
        return true;
    }
    public boolean requestPermissions(){
        return requestPermissions(getRuntimePermissions());
    }
    /**
     * 请求权限
     * @param permissions 权限列表
     */
    public boolean requestPermissions(String ... permissions){
        List<String> permissionList=new ArrayList<>();
        for(String permission:permissions){   //过滤被拒绝的权限
            if(this.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED){
                permissionList.add(permission);
            }
        }
        if(permissionList.size()>0) {
            String[] ps=  permissionList.toArray(new String[permissionList.size()]);
            this.requestPermissions(ps, REQUEST_BLUETOOTH_CODE);
            return true;
        }
        return false;
    }
    /**
     * 是否支持BLE
     * @return
     */
    public final boolean isSupportBle(Context context){
        PackageManager  packageManager = context.getPackageManager();
        return BluetoothAdapter.getDefaultAdapter() != null && packageManager != null && packageManager.hasSystemFeature(
                PackageManager.FEATURE_BLUETOOTH_LE
        );
    }
    /**
     * 蓝牙开启
     * @return
     */
    protected final boolean isBluetoothOpened(){
        return BluetoothAdapter.getDefaultAdapter()!=null && BluetoothAdapter.getDefaultAdapter().isEnabled();
    }
    /**
     * 打开蓝牙
     */
    protected void openBluetooth(){
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.S){
            if (requestPermissions(getRuntimePermissions()))
                return;
        }
        intentActivityResultLauncher.launch(intent);
    }

    public void connect(String mac){
        MeshServer.getInstance().connect(mac, new ConCallback() {
            @Override
            public void OnError(String mac, Throwable t) {
                showToast(String.format("error", t.getMessage()));
                isConnected=false;
                runOnUiThread(() -> {
                    DialogUtil.getInstance().hideLoadingDialog();
                    invalidateOptionsMenu();
                });
            }

            @Override
            public void OnConnecting(String mac) {
                isConnected = false;
                runOnUiThread(()->{
                    DialogUtil.getInstance().showLoadingDialog(self, "正在连接...");
                });
            }

            @Override
            public void OnConnectSuccess(String mac) {
                showToast("connect success");
                isConnected = true;
                runOnUiThread(()->{
                    DialogUtil.getInstance().hideLoadingDialog();
                    invalidateOptionsMenu();
                });
            }

            @Override
            public void OnInvalidDevice(String mac) {
                showToast("not target device");
                runOnUiThread(()->{
                    disconnect(false);
                });
            }

            @Override
            public void OnConnectTimeout(String mac) {
                showToast("connect timeout");
                isConnected = false;
                runOnUiThread(()->{
                    DialogUtil.getInstance().hideLoadingDialog();
                    invalidateOptionsMenu();
                });
            }

            @Override
            public void OnDisconnect(String mac, BluetoothDevice bluetoothDevice, int status) {
                isConnected = false;
                runOnUiThread(()->{
                    DialogUtil.getInstance().hideLoadingDialog();
                    invalidateOptionsMenu();
                });
                showToast("disconnect");
            }
        });
    }
    public void disconnect(boolean force){
        try {
            MeshServer.getInstance().disconnect(force);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public final void  showToast(String message){
        runOnUiThread(() -> ToastUtil.create(self,message));
    }
    ActivityResultLauncher<Intent> intentActivityResultLauncher  = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK) {
                    showToast("接受请求");
                } else if(result.getResultCode()==RESULT_CANCELED){
                    showToast("取消请求");
                }
            });
}
